/***
 * @author lhc
 * @description 借口获取数据基类,配置
 *
 */
import axios from "axios";
import qs from "qs";
import prompt from "/@/common/promptEnum";
import Utils from "/@/common/Utils";
import { loadEnv } from "@build/index";
import { useUserStoreHook } from "/@/store/modules/user";
import JSONBig from "json-bigint";
import { ElMessage } from "element-plus";
const { VITE_PROXY_DOMAIN, VITE_PROXY_DOMAIN_REAL, MODE } = loadEnv();

class LocalAxios {
  public axios: any;
  constructor(url: string) {
    this.axios = axios.create({
      baseURL: LocalAxios.getURL(url),
      timeout: 100000,
      withCredentials: true
    });
    this.transResponse();
    this.onRequest();
    this.onResponse();
  }

  private static getURL(url: string): string {
    if (url) {
      if (url.startsWith("http")) {
        return url;
      } else {
        if (MODE === "development") {
          return VITE_PROXY_DOMAIN + url;
        } else {
          return VITE_PROXY_DOMAIN_REAL + url;
        }
      }
    } else {
      if (MODE === "development") {
        return VITE_PROXY_DOMAIN;
      } else {
        return VITE_PROXY_DOMAIN_REAL;
      }
    }
  }

  private onRequest() {
    this.axios.interceptors.request.use(
      (config: any) => {
        /* config.startTime = new Date().getTime();
      console.log('拦截器生效');
      return config; */
        if (config.method === "post" || config.method === "put") {
          config.data = qs.stringify(Utils.exceptNull(config.data));
        } else {
          config.params = Utils.exceptNull(config.params);
        }
        // config.method === 'post'
        //   ? (config.data = qs.stringify(
        //     Utils.exceptNull(config.data)
        //      ))
        //   : (config.params = Utils.exceptNull(config.params));
        config.headers["Content-Type"] = "application/x-www-form-urlencoded";
        if (useUserStoreHook().$state.token) {
          config.headers["X-Access-Token"] = useUserStoreHook().$state.token;
        }
        return config;
      },
      (error: any) => {
        // Message.error('服务器Request出错')
        console.log(error, prompt.ERROR);
        return Promise.reject(error);
      }
    );
  }

  private transResponse() {
    this.axios.defaults.transformResponse = [
      (data: any) => {
        if (data.includes("<!DOCTYPE html>") || data.includes("login error")) {
          return JSON.stringify(data);
        }
        return JSONBig.parse(data);
      }
    ];
  }

  private onResponse() {
    this.axios.interceptors.response.use(
      (response: any) => {
        // if (response.status === 200 && UserModule.token) {
        //   if (response.request.responseURL) {
        //     if (response.request.responseURL.includes("service")) {
        //       // UserModule.LogOut();
        //     }
        //   }
        // }
        // if (response.status === 401) {
        //   UserModule.LogOut();
        // }
        /* console.log(
          `路由${
            response.config.url
            }请求成功，耗时${new Date().getTime() -
          response.config.startTime}ms`
        );
        return response.data; */
        if (response.data.code === 4) {
          ElMessage.error(response.data.msg);
        } else if (response.data.code !== 3) {
          return response;
        } else {
          if (VITE_PROXY_DOMAIN) {
            useUserStoreHook().logOut();
          } else {
            // UserModule.ResetToken();
            useUserStoreHook().logOut();
            // router.push("/");
          }
        }
      },
      (err: any) => {
        /* console.log(`错误信息 ${err.message}`);
        err.data = {
          code: -10000,
          data: '网络出错'
        };
        console.log(
          `路由${err.config.url}请求失败，耗时${new Date().getTime() -
          err.config.startTime}ms`
        );
        return Promise.resolve(err.data); */
        console.log("error");
        console.log(err);
        console.log(JSON.stringify(err));
        // Message.error('服务器Request出错')
        return Promise.reject(err);
      }
    );
  }
}

export default LocalAxios;
